/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年6月23日         Root.Lu
 */

package com.tianci.appstore.controller;

import android.content.ComponentName;
import android.content.Intent;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.aidl.ILitePMUninstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.paster.util.JsonUtil;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppDetailData;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.tianci.appstore.SearchActivity;
import com.tianci.appstore.audio.IAudio;
import com.tianci.appstore.database.AppStoreDB;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.framework.cache.Cache;
import com.tianci.appstore.ui.data.SkyAppDetailData;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppAction;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.detail.AppDownloadListener;
import com.tianci.appstore.ui.detail.OnDetailRefreshListener;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.AppDebug;
import com.tianci.appstore.utils.FileTools;

import org.json.JSONException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AppStoreDetailPageController extends AppStoreBaseController implements IAudio {
    private static AppStoreDetailPageController instance = new AppStoreDetailPageController();

    public static AppStoreDetailPageController getInstance() {
        return instance;
    }

    private static Cache<String, AppDetailData> appdetailCache = new Cache<String, AppDetailData>();

    private static final String SCENE_FORMAT = "com.tianci.appstore:AppDetailActivity";
    private HashMap<String, DownloadTask> taskMap = new HashMap<String, DownloadTask>();
    private String installing_apk = null;
    private OnDetailRefreshListener refreshListener = null;
    private AppDownloadListener downloadListener = null;
    private String id = null;
    private DownloadURL currentUrl = null;
    private AppDetailData appDetail = null;
    private boolean bInstalling = false;

    private AppStoreDetailPageController() {

    }

    public void init(String appId, OnDetailRefreshListener listener,
                     AppDownloadListener downloadlistener) {
        bInstalling = false;
        installing_apk = null;
        id = appId;
        currentUrl = null;
        refreshListener = listener;
        downloadListener = downloadlistener;
        runOnThread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        XServiceManager.getDownloaderService().setListener(downloaderStub);
                        XServiceManager.getLitePMService().addInstallListener(appPMStub);
                        XServiceManager.getLitePMService().addUninstallListener(appUninstallStub);
                        List<DownloadTask> list = XServiceManager.getDownloaderService()
                                .getTaskList();
                        synchronized (taskMap) {
                            taskMap.clear();
                            for (DownloadTask task : list)
                                taskMap.put(task.url, task);
                        }
                        appDetail = getAppDetail(id, "");
                        updateAppDetailUi(appDetail);
                        break;
                    } catch (RemoteException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                        updateAppDetailUi(null);
                    }
                }
            }
        });
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        id = "";
        currentUrl = null;
        installing_apk = null;
        downloadListener = new AppDownloadListener() {
            @Override
            public void onUpdateStatus(String appId, AppStatus status) {

            }

            @Override
            public void onUpdatePercent(String appId, int percent) {

            }
        };
        refreshListener = new OnDetailRefreshListener() {
            @Override
            public void onUpdate(SkyAppDetailData appDetail) {

            }
        };
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    XServiceManager.getDownloaderService().clearListener(downloaderStub);
                    XServiceManager.getLitePMService().removeInstallListener(appPMStub);
                    XServiceManager.getLitePMService().removeUninstallListener(appUninstallStub);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 删除详情页下载的图片
                FileTools.delAllFile(AppStoreDB.getInstance().getBigScreenPath());
            }
        });
    }

    private static Map<String, DownloadURL> urlMap = new HashMap<String, DownloadURL>();

    private static class DownloadURL {
        public String url;
        public String md5;

        @Override
        public String toString() {
            return "url:" + url + "  md5:" + md5;
        }
    }

    private DownloadURL getDownurl(String appid, String usercount) {
        try {
            DownloadURL downurl = null;
            synchronized (urlMap) {
                downurl = urlMap.get(appid);
            }
            if (downurl == null) {
                Map<String, String> m = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddressWithMD5(
                        Integer.valueOf(appid), usercount);
                if (m != null) {
                    downurl = new DownloadURL();
                    downurl.url = m.get("download");
                    downurl.md5 = m.get("md5");
                    urlMap.put(appid, downurl);
                }
            }
            LogUtils.d("download url:" + downurl);
            currentUrl = downurl;
            return downurl;
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("获取应用下载地址接口",
                    Android.throwable2String(e));
            System.out.println("错误原因：" + e.getErrormsg());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    private synchronized void handleDownload(DownloadURL download_url, String title, boolean logSent) {
        if (download_url != null) {
            String download_path = AppDataProvider.getInstance().getDownloadPath();
            try {
                DownloadTask task = taskMap.get(download_url.url);

                if (task == null) {
                    DownloadExtra extra = new DownloadExtra(appDetail.id,
                            appDetail.packageName, appDetail.iconUrl,
                            appDetail.title);
                    task = new DownloadTask(download_url.url);
                    task.title = title;
                    task.url = download_url.url;
                    task.filename = appDetail.packageName + ".apk";
                    task.extra = extra.toString();
                    if (download_url.md5 != null && !download_url.md5.equals(""))
                        task.md5 = download_url.md5;
                    final DownloadTask _task = task;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            downloadListener.onUpdateStatus(_task.ID,
                                    AppStatus.WAITING);
                        }
                    });
                    synchronized (taskMap) {
                        taskMap.put(download_url.url, task);
                    }
                    if (!logSent)
                        sendBtnClickLOG("下载", Integer.valueOf(extra.appid),
                                extra.title);// getString(R.string.detail_download));
                    else
                        sendBtnClickLOG("升级", Integer.valueOf(extra.appid),
                                extra.title);// getString(R.string.detail_upgrade));
                }
                XServiceManager.getDownloaderService().add(task);
                XServiceManager.getDownloaderService().start(task);
                task = XServiceManager.getDownloaderService().refresh(task);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public void handlerDetailAction(final String appid, final String title, final String pkg,
                                    final AppAction action) {
        runOnThread(new Runnable() {
            private boolean logSent = false;

            @Override
            public void run() {
                LogUtils.d("handlerDetailAction action:" + action + " appid:" + appid);
                DownloadURL download_url = getDownurl(appid, "");
                switch (action) {
                    case ACTION_UPGRADE: // 升级
                        logSent = true;
                    case ACTION_DOWNLOAD: // 下载
                        if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                            break;
                        LogUtils.d("download_url:" + download_url);
                        handleDownload(download_url, title, logSent);
                        break;
                    case ACTION_PAUSE: // 暂停
                        try {
                            DownloadTask task = null;
                            synchronized (taskMap) {
                                task = taskMap.get(download_url.url);
                            }
                            if (task != null) {
                                // AppDataProvider.getInstance().getServiceData().stop(task);
                                XServiceManager.getDownloaderService().stop(task);
                                DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                        DownloadExtra.class);
                                sendBtnClickLOG("暂停", Integer.valueOf(extra.appid), extra.title);// getString(R.string.detail_pause));
                            }

                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case ACTION_CONTINUE: // 继续下载
                        try {
                            DownloadTask task = null;
                            synchronized (taskMap) {
                                task = taskMap.get(download_url.url);
                            }
                            if (task != null) {
                                if (task.url == null) {
                                    while (task.url == null)
                                        task.url = download_url.url;
                                }
                                XServiceManager.getDownloaderService().start(task);
                                // AppDataProvider.getInstance().getServiceData().start(task);
                                DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                        DownloadExtra.class);
                                sendBtnClickLOG("继续下载", Integer.valueOf(extra.appid), extra.title);// getString(R.string.detail_contiue_download));

                                final DownloadTask _task = task;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        downloadListener
                                                .onUpdateStatus(_task.ID, AppStatus.WAITING);
                                    }
                                });
                            }
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case ACTION_INSTALL: // 安装
                        try {
                            DownloadTask task = null;
                            synchronized (taskMap) {
                                task = taskMap.get(download_url.url);
                            }
                            if (task != null) {
                                task = XServiceManager.getDownloaderService().refresh(task);
                                installing_apk = task.savepath + task.filename;
                                InstallParams params = new InstallParams();
                                params.setFrom(InstallParams.INSTALL_FROM.COOCAA_MARKET);
                                XServiceManager.getLitePMService().install(installing_apk, CoocaaApplication.isRoot(), params);
                                DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                        DownloadExtra.class);
                                sendBtnClickLOG("安装", Integer.valueOf(extra.appid), extra.title);// getString(R.string.detail_install));
//如果是静默安装，则可以不用强制去改变状态
//                                if (CoocaaApplication.isRoot()) {
//                                    runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            // TODO Auto-generated method stub
//                                            downloadListener.onUpdateStatus(id,
//                                                    AppStatus.INSTALLING);
//                                        }
//                                    });
//                                }
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                    case ACTION_CANCEL: // 取消
                        logSent = true;
                    case ACTION_DELETE: // 删除
                        try {
                            DownloadTask task = null;
                            synchronized (taskMap) {
                                task = taskMap.get(download_url.url);
                            }
                            if (task != null) {
                                XServiceManager.getDownloaderService().delete(task);
                                DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                        DownloadExtra.class);
                                if (logSent)
                                    sendBtnClickLOG("取消", Integer.valueOf(extra.appid), extra.title); // sendBtnClickLOG(getString(R.string.detail_cancle));
                                else
                                    sendBtnClickLOG("删除", Integer.valueOf(extra.appid), extra.title);// getString(R.string.detail_install));
                            }
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case ACTION_UNINSTALL: // 卸载
                        try {
                            XServiceManager.getLitePMService().uninstall(pkg,
                                    CoocaaApplication.isRoot());
                            sendBtnClickLOG("卸载", -1, pkg);// getString(R.string.detail_uninstall));
                            if (CoocaaApplication.isRoot()) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        downloadListener.onUpdateStatus(id, AppStatus.UNINSTALLING);
                                    }
                                });
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                    case ACTION_LAUNCH: // 打开
                        try {
                            List<AppInfo> list = XServiceManager.getLitePMService()
                                    .getInstalledApps();
                            for (AppInfo app : list) {
                                if (app.pkgName.equals(pkg)) {
                                    XServiceManager.getLitePMService().startAppByComponentName(mContext.getClass().getName(), false,
                                            new ComponentName(app.pkgName, app.mainActivity));
                                    sendBtnClickLOG("打开", -1, pkg);// getString(R.string.app_open));
                                    break;
                                }
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                    case ACTION_NULL: // 不做任何操作
                    default:
                        break;
                }
            }
        });
    }

    private void updateAppDetailUi(final AppDetailData appDetail) {
        runOnThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    if (appDetail != null) {
                        AppStatus appStatus = AppDataProvider.getInstance().getAppStatus(
                                appDetail.packageName, appDetail.versionCode);
                        LogUtils.d("appStatus:" + appStatus);
                        final SkyAppDetailData detailData = new SkyAppDetailData(appDetail.id,
                                appDetail.iconUrl, appDetail.title, appDetail.packageName,
                                appDetail.versionCode, appDetail.updateInfo, appDetail.infoList,
                                appStatus, appDetail.introduction, appDetail.screenShotsPreview,
                                appDetail.screenShotsBig, appDetail.screenShots,
                                appDetail.superscript);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                refreshListener.onUpdate(detailData);
                            }
                        });
                        DownloadURL downurl = getDownurl(appDetail.id, "");
                        DownloadTask task = taskMap.get(downurl.url);
                        if (task != null) {
                            final DownloadTask _task = XServiceManager.getDownloaderService()
                                    .refresh(task);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    if (_task.info.length > 0) {
                                        int percent = (int) (_task.info.current * 100 / _task.info.length);
                                        downloadListener.onUpdatePercent(_task.ID, percent);
                                    }
                                }
                            });
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                refreshListener.onUpdate(null);
                            }
                        });
                    }
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    private AppDetailData getAppDetail(String appid, String version) {
        AppDetailData app = appdetailCache.get(appid);
        try {
            if (app == null) {
                try {
                    app = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppDetail(appid, version);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            LogAPIForAppStore.reportInterfaceError("通过包名获取应用信息", Android.throwable2String(e));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    refreshListener.onUpdate(null);
                    TipToast.getInstance(mContext).showTipToast("获取后台数据超时！");
                }
            });
            e.printStackTrace();
            app = null;
        }
        if (app != null)
            appdetailCache.add(appid, app);
        return app;
    }

    @Override
    public String getModuleName() {
        // TODO Auto-generated method stub
        return "";
    }

    private ILitePMUninstallListener.Stub appUninstallStub = new ILitePMUninstallListener.Stub() {

        @Override
        public void onUninstallStart(AppInfo appInfo) throws RemoteException {
            if (appInfo.appName.equals(appDetail.packageName)) {
                bInstalling = true;
                if (CoocaaApplication.isRoot()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            downloadListener.onUpdateStatus(id, AppStatus.UNINSTALLING);
                        }
                    });
                }
            }
        }

        @Override
        public void onUninstallEnd(final AppInfo appInfo, int arg1, final String arg2) throws RemoteException {
            if (appInfo.pkgName.equals(appDetail.packageName)) {
                bInstalling = false;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (appDetail != null && appDetail.packageName.equals(appInfo.pkgName))
                            updateAppDetailUi(appDetail);
                    }
                });
            }
        }
    };

    private ILitePMInstallListener.Stub appPMStub = new ILitePMInstallListener.Stub() {
        @Override
        public void onInstallStart(String apkfile, AppInfo appInfo, final InstallParams params) throws RemoteException {
            // TODO Auto-generated method stub
            if (appInfo.pkgName.equals(appDetail.packageName)) {
                bInstalling = true;
                if (CoocaaApplication.isRoot()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            downloadListener.onUpdateStatus(id, AppStatus.INSTALLING);
                        }
                    });
                }
            }
        }

        @Override
        public void onInstallEnd(String apkfile, final AppInfo appInfo, int success, String extra, final InstallParams params)
                throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("onInstallEnd:" + installing_apk + "  success:" + success);
            if (installing_apk != null && installing_apk.equals(apkfile)) {
                bInstalling = false;
                if (success == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AppStatus appStatus = AppDataProvider.getInstance().getAppStatus(
                                    appInfo.pkgName, String.valueOf(Android.getVersionCode(mContext, appInfo.pkgName)));
                            downloadListener.onUpdateStatus(id, appStatus);
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            downloadListener.onUpdateStatus(id, AppStatus.DOWNLOADED);
                        }
                    });
                }
            }
        }
    };

    private IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {

        @Override
        public void onReady(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            if (currentUrl == null)
                return;
            AppDebug.debug("AppStoreDetailPageController onReady " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl.url));
            if (task.ID.equals(currentUrl.url)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        downloadListener.onUpdateStatus(id, AppStatus.WAITING);
                    }
                });
            }
        }

        @Override
        public void onPrepare(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStart(final DownloadTask task) throws RemoteException {
            if (currentUrl == null)
                return;
            AppDebug.debug("AppStoreDetailPageController onStart " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl.url));
            if (task.ID.equals(currentUrl.url)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        downloadListener.onUpdateStatus(id, AppStatus.DOWNLOADING);
                    }
                });
            }
        }

        @Override
        public void onStop(final DownloadTask task) throws RemoteException {
            if (currentUrl == null)
                return;
            AppDebug.debug("AppStoreDetailPageController onStop " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl.url));
            if (task.ID.equals(currentUrl.url)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        downloadListener.onUpdateStatus(id, AppStatus.DOWNLOAD_PAUSED);
                    }
                });
            }
        }

        @Override
        public void onFinish(final DownloadTask task) throws RemoteException {
            if (currentUrl == null)
                return;
            AppDebug.debug("AppStoreDetailPageController onFinish " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl.url));
            if (task.ID.equals(currentUrl.url)) {
                installing_apk = task.savepath + task.filename;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        downloadListener.onUpdateStatus(id, AppStatus.DOWNLOADED);
                    }
                });
            }
        }

        @Override
        public void onDelete(final DownloadTask task) throws RemoteException {
            if (currentUrl == null)
                return;
            AppDebug.debug("AppStoreDetailPageController onDelete " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl.url));
            synchronized (taskMap) {
                taskMap.remove(task.url);
            }
            final DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            if (task.ID.equals(currentUrl.url) && !bInstalling) {
                if (XServiceManager.getLitePMService().isInstalled(extra.pkgname)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            downloadListener.onUpdateStatus(id, AppStatus.INSTALLED);
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            downloadListener.onUpdateStatus(id, AppStatus.NOT_DOWNLOADED);
                        }
                    });
                }
            }
        }

        @Override
        public void onProcessInfo(final DownloadTask task, final ProcessInfo info)
                throws RemoteException {
            if (currentUrl == null)
                return;
            AppDebug.debug("onProcessInfo:" + info + "  task.ID.equals(id):" + task.ID.equals(currentUrl)
                    + "  bInstalling:" + bInstalling);
            if (task.ID.equals(currentUrl.url) && !bInstalling) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        downloadListener.onUpdatePercent(id, info.percent);
                    }
                });
            }
        }

        @Override
        public void onError(final DownloadTask task, DownloadError error) throws RemoteException {
            if (currentUrl == null)
                return;
            AppDebug.debug("AppStoreDetailPageController onError " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl.url));
            if (task.ID.equals(currentUrl.url)) {
                if (error.errcode == DownloadError.ERRCODE_MD5_CHECK_ERROR)
                    return;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        downloadListener.onUpdateStatus(id, AppStatus.DOWNLOAD_PAUSED);
                        // downloadListener.onUpdateStatus(task.task.id, AppStatus.NOT_DOWNLOADED);
                    }
                });
            }
        }
    };

    @Override
    public String getCommand() {
        String json = "";
        String scene = SCENE_FORMAT;// String.format(SCENE_FORMAT, appDetail.packageName);
        HashMap<String, String[]> hashMap = getGlobalCommand();
        hashMap.put("下载", new String[]{"下载", "开始下载"});
        hashMap.put("打开", new String[]{"打开", "打开" + appDetail.title});
        hashMap.put("暂停", new String[]{"暂停"});
        hashMap.put("卸载", new String[]{"卸载", "开始卸载"});
        hashMap.put("取消", new String[]{"取消", "取消下载"});
        hashMap.put("更新", new String[]{"更新", "更新" + appDetail.title});
        hashMap.put("继续", new String[]{"继续", "继续下载"});
        try {
            json = JsonUtil.makeScenceJson(scene, hashMap, null, null).toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        LogUtils.d("KKK", "onQuery:" + json);
        return json;
    }

    public HashMap<String, String[]> getGlobalCommand() {
        HashMap<String, String[]> command = new HashMap<String, String[]>();
        command.put("back", new String[]{"返回"});
        command.put("exit", new String[]{"退出"});
        command.put("search", new String[]{"搜索"});
        return command;
    }

    @Override
    public boolean exeCommand(Intent arg0) {
        LogUtils.d("KKK", "onExecute:1111");
        LogUtils.d("KKK", "onExecute:" + arg0.toString());
        String scene = String.format(SCENE_FORMAT, appDetail.packageName);
        if (arg0.hasExtra("_scene") && arg0.getStringExtra("_scene").equals(scene)) {
            if (arg0.hasExtra("_command")) {
                AppStatus appStatus = null;
                try {
                    appStatus = AppDataProvider.getInstance().getAppStatus(appDetail.packageName,
                            appDetail.versionCode);
                } catch (Exception e) {
                    return false;
                }
                String command = arg0.getStringExtra("_command");
                LogUtils.d("KKK", "onExecute:" + command);
                if ("下载".equals(command)) {
                    switch (appStatus) {
                        case NOT_DOWNLOADED:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_DOWNLOAD);
                            break;
                        default:
                            break;
                    }
                } else if ("打开".equals(command)) {
                    switch (appStatus) {
                        case HAS_NEW_VERSION:
                        case INSTALLED:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_LAUNCH);
                            break;
                        default:
                            break;
                    }
                } else if ("暂停".equals(command)) {
                    switch (appStatus) {
                        case DOWNLOADING:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_PAUSE);
                            break;
                        default:
                            break;
                    }
                } else if ("卸载".equals(command)) {
                    switch (appStatus) {
                        case HAS_NEW_VERSION:
                        case INSTALLED:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_UNINSTALL);
                            break;
                        default:
                            break;
                    }
                } else if ("取消".equals(command)) {
                    switch (appStatus) {
                        case DOWNLOADING:
                        case DOWNLOAD_PAUSED:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_CANCEL);
                            break;
                        default:
                            break;
                    }
                } else if ("更新".equals(command)) {
                    switch (appStatus) {
                        case HAS_NEW_VERSION:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_UPGRADE);
                            break;
                        default:
                            break;
                    }
                } else if ("继续".equals(command)) {
                    switch (appStatus) {
                        case DOWNLOAD_PAUSED:
                            handlerDetailAction(appDetail.id, appDetail.title,
                                    appDetail.packageName, AppAction.ACTION_CONTINUE);
                            break;
                        default:
                            break;
                    }
                } else if (command.equals("back")) {
                    Android.simulateKey(KeyEvent.KEYCODE_BACK, 0);
                    Android.simulateKey(KeyEvent.KEYCODE_BACK, 1500);
                } else if (command.equals("exit")) {
                    Android.simulateKey(KeyEvent.KEYCODE_BACK, 0);
                    System.exit(0);
                } else if (command.equals("search")) {
                    Android.simulateKey(KeyEvent.KEYCODE_BACK, 0);
                    String key = arg0.getStringExtra("keyword");
                    LogUtils.d("luwei", "the key is " + key);
                    Intent intent2 = new Intent(mContext, SearchActivity.class);
                    intent2.putExtra(SearchActivity.SEARCH_KEY, key);
                    mContext.startActivity(intent2);
                }
            }
        }
        return false;
    }

    // @Override
    // public void installEvent(final Intent i)
    // {
    // // TODO Auto-generated method stub
    // runOnThread(new Runnable()
    // {
    // @Override
    // public void run()
    // {
    // // TODO Auto-generated method stub
    // String packageName = i.getDataString().substring(8);
    // if (appDetail != null && appDetail.packageName.equals(packageName))
    // updateAppDetailUi(appDetail);
    // }
    // });
    // }
    //
    // @Override
    // public void uninstallEvent(final Intent i)
    // {
    // // TODO Auto-generated method stub
    // runOnThread(new Runnable()
    // {
    // @Override
    // public void run()
    // {
    // // TODO Auto-generated method stub
    // String packageName = i.getDataString().substring(8);
    // if (appDetail != null && appDetail.packageName.equals(packageName))
    // updateAppDetailUi(appDetail);
    // }
    // });
    // }
}
